package com.yj.cmp.sdk.fusioncompute.compute.task;

import com.yj.cmp.sdk.fusioncompute.common.utils.RequestUtils;
import com.yj.cmp.sdk.fusioncompute.compute.task.vo.TaskListVo;
import com.yj.cmp.sdk.fusioncompute.compute.task.vo.TaskVo;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import retrofit2.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Zhai
 * @date 2021/9/1 11:16
 */
@Component
public class FcTaskApi {
    private final Logger log = LoggerFactory.getLogger(FcTaskApi.class);

    FcTaskService fcTaskService;

    public FcTaskApi(FcTaskService fcTaskService) {
        this.fcTaskService = fcTaskService;
    }

    /**
     * 查询单个任务
     *
     * @param headers
     * @param taskId
     * @return
     * @throws Exception
     */
    public TaskVo getTaskDetail(Map<String, Object> headers, String taskId) throws Exception {
        log.info("taskId = " + taskId);
        Response<TaskVo> response = fcTaskService.getTaskDetail(headers, taskId).execute();
        RequestUtils.isSuccessful(response);
        if (null == response.body()) {
            throw new RuntimeException("查询指定任务为空");
        }
        log.info("TaskVo = " + response.body());
        return response.body();
    }

    /**
     * 过滤查询任务
     *
     * @param headers
     * @param queryParam
     * @return
     * @throws Exception
     */
    public List<TaskListVo.TasksDTO> getTaskList(Map<String, Object> headers, Map<String, Integer> queryParam) throws Exception {
        log.info("Query param is " + queryParam);

        Response<TaskListVo> response = fcTaskService.getTaskList(headers, queryParam).execute();
        RequestUtils.isSuccessful(response);
        List<TaskListVo.TasksDTO> tasksDTOList = new ArrayList<>(response.body().getTasks());
        queryParam.put("limit", queryParam.get("limit") == null ? 100 : queryParam.get("limit"));
        Integer limit = queryParam.get("limit");
        if (null == response.body()) {
            log.info("tasksDTOList is empty!");
            return tasksDTOList;
        }
        int page = (int) Math.ceil(new Double(response.body().getTotal()) / limit);
        for (int i = 1; i <= page; i++) {
            queryParam.put("offset", (i - 1) * limit);
            tasksDTOList.addAll(fcTaskService.getTaskList(headers, queryParam).execute().body().getTasks());
        }
        log.info("task list is" + tasksDTOList);
        return tasksDTOList;
    }

    /**
     * 取消任务
     *
     * @param headers
     * @param taskId
     * @throws Exception
     */
    public int cancelTask(Map<String, Object> headers, String taskId) throws Exception {
        log.info("taskId = " + taskId);
        Response<ResponseBody> response = fcTaskService.cancelTask(headers, taskId).execute();
        return response.code();
    }
}





























